package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.WmNewsMessageConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsMaterialService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews>  implements WmNewsService {


    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    WmNewsMaterialService wmNewsMaterialService;

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Autowired
    WmNewsMapper wmNewsMapper;

    @Autowired
    WmUserMapper wmUserMapper;



    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //1. 检查参数
        if (dto==null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery();

        //2. 根据传参条件查询

        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        if (dto.getKeyword() != null) {
            queryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getChannelId() != null) {
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            queryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3. 分页查询
        Page<WmNews> wmNewsPage = new Page<>(dto.getPage(), dto.getSize());

        IPage<WmNews> pageResult = page(wmNewsPage, queryWrapper);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal(), pageResult.getRecords());
        //4. 返回
        result.setHost(webSite);

        return result;
    }

    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto) {
        //1. 检验参数
        if (wmNewsDto == null || StringUtils.isEmpty(wmNewsDto.getContent())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"文章内容不能为空");
        }
        Short status = wmNewsDto.getStatus();
        if (status == null || status.intValue() != 0 && status.intValue() != 1) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "文章状态错误");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2. 获取文章信息

        WmNews wmNews = new WmNews();

        BeanUtils.copyProperties(wmNewsDto, wmNews);

        //3. 保存或者修改文章

        //3.1 如过文章是自动的则需要吧type设置为null
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        List<String> image = wmNewsDto.getImages();
        String images = imagesTostr(image);
        wmNews.setImages(images);

        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(user.getId());
        wmNews.setSubmitedTime(new Date());

        saveOrUpdateWmNews(wmNews);

        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_DRAFT_STATUS)) {
            return ResponseResult.okResult();
        }

        // 获得图片路径
        List<Map> contentMaps = JSONArray.parseArray(wmNewsDto.getContent(), Map.class);

        List<String> urlList = parseContentImages(contentMaps);

         // 如果图片列表不为空则进行内容图片素材关联
        if (urlList != null && urlList.size() > 0) {
            saveRelativeInfo(wmNews.getId(),urlList,WemediaConstants.WM_CONTENT_REFERENCE);
        }



        // 进行封面图片素材关联
        saveRelativeInfoForCover(wmNewsDto,wmNews,urlList);

        // 发送自动审核文章的信息
        Map map = new HashMap();
        map.put("wmNewsId",wmNews.getId());
        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(map));
        log.info("自动审核的消息通知成功发送  主题:{}  文章id:{}",NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC,wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findById(Integer id) {
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult deleteById(Integer id) {

        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);

        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已经发布啦，不可以动奥");
        }

        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getNewsId, wmNews.getId()));

        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto wmNewsDto) {

        // 1.检查参数

        if (wmNewsDto==null||wmNewsDto.getId()==null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2. 获取news
        WmNews wmNews = getById(wmNewsDto.getId());
        // 判断状态  未发布的不能改变上架状态

        if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_PUBLISH_STATUS)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "没发布的文章要怎么上架呢");
        }
        //3. 改变上架状态 并返回
        if (wmNews.getEnable() != null && wmNews.getEnable() > -1 && wmNews.getEnable() < 2) {
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, wmNewsDto.getId())
            .set(WmNews::getEnable,wmNewsDto.getEnable()));
        }

        if (wmNews.getArticleId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("enable",wmNews.getEnable());
            map.put("articleId",wmNews.getArticleId());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);



    }

    @Override
    public ResponseResult updateWmNews(WmNews wmNews) {

        boolean result = this.updateById(wmNews);

        return ResponseResult.okResult(result);
    }

    @Override
    public ResponseResult findWmUserById(Integer id) {
        WmNews wmNews = this.getById(id);
        return ResponseResult.okResult(wmNews);
    }

    @Override
    public ResponseResult<List<Integer>> findRelease() {
        //找出状态为4/8且发布时间小于当前时间的news
        List<WmNews> wmNewsList = this.wmNewsMapper.selectList(Wrappers.<WmNews>lambdaQuery()
                .in(WmNews::getStatus, 4, 8)
                .le(WmNews::getPublishTime, new Date())
                .select(WmNews::getId));

        // 根据stream流获得newsID集合
        List<Integer> newsIds = wmNewsList.stream().map(WmNews::getId).collect(Collectors.toList());
        //返回
        return ResponseResult.okResult(newsIds);
    }

    @Override
    public ResponseResult findNewsList(NewsAuthDto newsAuthDto) {
       // 校验参数
        newsAuthDto.checkParam();
        // 设置查询条件
        if (StringUtils.isNotEmpty(newsAuthDto.getTitle())) {
            newsAuthDto.setTitle("%" + newsAuthDto.getTitle() + "%");
        }
        Integer page = newsAuthDto.getPage();
        newsAuthDto.setPage((page-1)*newsAuthDto.getSize());
        // 根据查询条件查询

        List<WmNewsVo> listAndPage=wmNewsMapper.findListAndPage(newsAuthDto);
        Long count = wmNewsMapper.findListCount(newsAuthDto);
        PageResponseResult result = new PageResponseResult(page, newsAuthDto.getSize(), count, listAndPage);

        result.setHost(webSite);

        return result;
    }

    @Override
    public ResponseResult findWmNewsVo(Integer id) {

        // 检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 查询文章信息
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 查询 作者
        WmUser wmUser = null;
        if (wmNews.getUserId() != null) {
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        // 封装VO返回
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews, wmNewsVo);
        if (wmUser != null) {
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult result = ResponseResult.okResult(wmNewsVo);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult authPass(NewsAuthDto dto) {
        // 1. 检查参数
        dto.checkParam();
        //2. 调用更新状态方法
        return  updateStatus(WemediaConstants.WM_NEWS_AUTH_PASS, dto);
    }


    @Override
    public ResponseResult authFail(NewsAuthDto dto) {
        // 1. 检查参数
        dto.checkParam();
        //2. 调用更新状态方法  2是未通过审核的
        return  updateStatus(WemediaConstants.WM_NEWS_AUTH_FAIL, dto);
    }
    private ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        //1. 检查参数
        dto.checkParam();
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.改变状态
        wmNews.setStatus(status);
        if (StringUtils.isNotEmpty(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        // 4. 更新数据
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    private void saveRelativeInfoForCover(WmNewsDto wmNewsDto, WmNews wmNews, List<String> urlList) {

        List<String> images = wmNewsDto.getImages();
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNewsDto.getType())) {
            if (urlList == null || urlList.size() == 0) {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            } else if (urlList.size() > 0 && urlList.size() < 2) {
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = urlList.stream().limit(1).collect(Collectors.toList());
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = urlList.stream().limit(3).collect(Collectors.toList());
            }
            if (images != null && images.size() > 0) {
                wmNews.setImages(imagesTostr(images));
                updateById(wmNews);
            }
        }
        if (images != null && images.size() >= 0) {
            images = images.stream().map(url -> url.replaceAll(webSite, "")).collect(Collectors.toList());
            saveRelativeInfo(wmNews.getId(), images, WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    private void saveRelativeInfo(Integer id, List<String> urlList, Short refType) {

       //  搜索素材列表
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                .in(WmMaterial::getUrl, urlList));

        if (wmMaterials == null || wmMaterials.size() == 0) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "指定素材不存在");
        }

        //  提取素材中的id和url

        Map<String, Integer> urlAndIdMap = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        // 判断urlAndIdMap中有无脏数据，是否和内容中的每一个素材都对应上

        ArrayList<Integer> materIds = new ArrayList<>();
        for (WmMaterial wmMaterial : wmMaterials) {
            if (!urlAndIdMap.containsKey(wmMaterial.getUrl())) {
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的素材不见啦");
            }
            materIds.add(urlAndIdMap.get(wmMaterial.getUrl()));
        }
        wmNewsMaterialMapper.saveRelations(materIds, id, refType);

    }

    private void saveOrUpdateWmNews(WmNews wmNews) {
        if (wmNews.getId()==null) {
            save(wmNews);
        }

        wmNewsMaterialService.remove(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));

        updateById(wmNews);
    }


    private String imagesTostr(List<String> image) {
        if (image != null && image.size() > 0) {
            String images = image.stream().map((url) -> url.replaceAll(webSite, ""))
                    .collect(Collectors.joining(","));
            return images;
        }
        return null;
    }
    private List<String> parseContentImages(List<Map> contentMaps) {
        List<String> list = contentMaps.stream().filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .map(url -> url.replaceAll(webSite, ""))
                .collect(Collectors.toList());

        return list;
    }

}
